package cn.com.qtgl.apis.iam.comp.service;

import cn.com.qtgl.apis.builtin.model.vo.Post;
import cn.com.qtgl.apis.iam.model.entity.LeaderPost;
import cn.melonlib.cores.commons.comp.service.impl.WorkerBasicService;
import cn.melonlib.cores.model.anno.*;
import cn.melonlib.objects.maps.JsonMap;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.Collections;
import java.util.List;


@WorkerComment("领导岗位管理")
@Service
@WorkerService(
        module = "apis"
        ,model = @WorkerModel(
                modelType = LeaderPost.class
)
)
public class LeaderPostService extends WorkerBasicService<LeaderPost> {

    @Resource
    private IamCacheService iamCacheService;

    @Transactional(value = Transactional.TxType.REQUIRED,rollbackOn = Exception.class)
    @WorkerStore(errorTip = "设置失败",successTip = "设置成功")
    @WorkerComment("设置领导岗位")
    public int setBatchs(@WorkerParameter(value = "posts",comment = "设置领导岗位",required = true) List<String> posts) throws Exception{
        int rowNum=dao.updateQl("delete from LeaderPost", Collections.emptyList());
        JsonMap<Post> postMap=iamCacheService.postMap();
        rowNum+=posts.stream().filter(p-> postMap.keySet().contains(p)).map(p->postMap.get(p)).reduce(0,(row,post)->{
            LeaderPost leaderPost=new LeaderPost();
            try {
                leaderPost.setPost(getJsonMapper().writeValueAsString(post));
            } catch (JsonProcessingException e) {
                logger.error(e.getMessage(),e);
            }
            leaderPost.setPostCode(post.getCode());
            return  row+1;
        },(row,post)->null);
        return rowNum;
    }
}
